<template>
  <template v-if="hasInfo">
    <cover-image v-if="banner" class="banner" :src="banner" size="@480w_270h" :webp="false" /> 
    <div class="title-wrap">
      <h1 class="title">{{ info.title }}</h1>
      <div class="info">
          <span v-if="type" class="type">{{ type }}</span>
          <span v-if="time" class="time">{{ time }}</span>
          <span v-if="view" class="view">{{ view }}阅读</span>
      </div>
    </div>
    <div v-if="author" class="author-wrap" @click="handleSpace">
        <avatar          
          class="face"
          size="small"
          :src="author.face"
          :vip="author.vip.vipStatus"
          :official="author.official_verify"
        />
        <span class="name">{{ author.name }}</span>
        <van-button class="follow" size="small" :disabled="author.is_followed">{{author.is_followed ? '已关注' : '关注'}}</van-button>                                
    </div>
    <article-content v-if="articleContent" :info="info" :content="formatContent" :tags="articleContent.tags"></article-content>
    <article-recommend v-if="recommend" :list="recommend.articles"></article-recommend>
    <article-comment v-if="comments" class="comment-wrap" :comments="comments"></article-comment>
  </template>
</template>

<script>
import { reactive, toRefs, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { Button as VanButton } from 'vant'
import ArticleContent from './content'
import ArticleRecommend from './recommend'
import Avatar from '@/components/Avatar'
import ArticleComment from '@/components/Comment'
import CoverImage from '@/components/CoverImage'
import { articleApi } from '@/api'
import { dateFormat, formatNumber } from '@/utils'
export default {
  name: 'Article',
  components: {
    Avatar,
    ArticleContent,
    ArticleRecommend,
    ArticleComment,
    CoverImage,
    VanButton
  },
  props: {
    id: {
      type: [Number, String]
    }
  },
  setup(props) {
    const router = useRouter()
    const params = reactive({
      info: null,
      articleContent: null,
      formatContent: null,
      recommend: null,
      comments: null,
      videos: null,
      hasInfo: computed(() => !!params.info),
      banner: computed(() => params.info?.banner_url ?? ''),
      hasContent: computed(() => !!params.articleContent),
      type: computed(() => params.articleContent?.type ?? ''),
      time: computed(() => {
        return params.hasContent ? dateFormat(new Date(params.articleContent.timestamp*1000), 'MM-dd') : ''
      }),
      videoIds: computed(() => params.articleContent?.videoIds ?? []),
      tags: computed(() => params.articleContent?.tags ?? []),
      view: computed(() => formatNumber(params.info?.stats?.view ?? 0)),
      author: computed(() => params.recommend?.author ?? null)
    })


    const initData = async () => {
        try {
            await getInfo()
            await getContent()
            await getContentVideos()
            await getRecommend()        
            await getComments()
        } catch (error) {
          console.log(error)
        }
    }

    const getInfo = async () => {
      try {
        const { data } = await articleApi.getInfo({
            id: props.id
        })
        if (data) {
          params.info = data
        }
      } catch (error) {
        throw new Error(error)
      }
    }

    const getContent = async () => {
      try {
        const { data } = await articleApi.getContent({
          id: props.id
        })
        if (data) {
          params.articleContent = data
          params.formatContent = data.content          
        }
      } catch (error) {
          console.log(error)
      }
    }

    const getContentVideos = async () => {
      try {
        if (params.videoIds.length === 0) {
            return
        }
        const { data } = await articleApi.getContentVideo({
            id: props.id,
            ids: params.videoIds.join(',')
        })
        if (data) {
            let fcontent = ''
            params.videos = data
            for (const value of params.videoIds.values()) {
                const ids = value.split(',')
                const htms = []
                for (const id of ids.values()) {
                    htms.push(parseVideo(data[id]))
                }

                fcontent = params.articleContent.content.replace(`<i data-ids="${value}"></i>`, htms.join(''))
            }
            params.formatContent = fcontent
        }
      } catch (error) {
        console.log(error)
      }
    }

    const parseVideo = (video) => {
        const html = `
            <div class="video-item">
                <a class="video-link" data-bvid="${video.bvid}"></a>
                <div class="video-cover">
                    <img class="img" src="${video.pic}@300w_188h" />
                </div>
                <div class="video-info">
                    <div class="video-title">${video.title}</div>
                    <div class="video-author">
                        <i class="fa fa-up-zhu"></i>
                        <span class="name">${video.owner.name}</span>
                    </div>
                </div>
            </div>
        `
        return html
    }

    const getRecommend = async () => {
      try {
        const { data } = await articleApi.getRecommend({
          aid: props.id
        })
        if (data) {
          params.recommend = data            
        }
      } catch (error) {
        console.log(error)
      }
    }

    const getComments = async () => {
      try {
        const { data } = await articleApi.getComments({
            oid: props.id
        })
        if (data) {
          params.comments = data.replies          
        }
      } catch (error) {
        console.log(error)
      }
    }

    const handleSpace = () => {
      router.push({
        name: 'space',
        params: {
          mid: params.author.mid
        }
      })
    }

    watch(() => props.id, () => {
      initData()
    }, {
      immediate: true
    })

    return {
      ...toRefs(params),
      handleSpace
    }
  }
}
</script>

<style lang="scss" scoped>
.banner{
    padding-bottom: 210/375*100%;
}

.title-wrap{
    padding: 15px 16px 20px;
    .title{
      font-size: 28px;
      color: $color-text-primary;
      margin: 0;
      margin-bottom: 10px;
      line-height: 1.4;
    }
    .info {
      font-size: 12px;
      color: $color-text-secondary;
      span{
        margin-right: 4px;
      }
    }
}

.author-wrap{
    display: flex;
    align-items: center;
    padding: 14px;
    .face{
      margin-right: 10px;
    }
    .name{
      flex: 1;
      color: $color-text-regular;
      font-size: 16px;
    }
    .follow{
      background-color: $theme-color;
      color: $color-white;
    }
}

.comment-wrap {
  border-top: 20px solid #f3f4f4;
}
</style>